package com.ccc.hotsearch.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ccc.hotsearch.model.HotItem;
import com.ccc.hotsearch.model.PlatformTypeEnum;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BaiduHotSearchServiceImpl implements HotSearchService {

    private static final String BAIDU_API_URL = "https://top.baidu.com/api/board?platform=wise&tab=realtime";

    @Override
    public PlatformTypeEnum getPlatformType() {
        return PlatformTypeEnum.BAIDU;
    }

    @Override
    public List<HotItem> getHotSearch() {
        try {
            return getHotSearchFromAPI();
        } catch (Exception e) {
            System.err.println("获取百度热搜失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    private List<HotItem> getHotSearchFromAPI() {
        List<HotItem> items = new ArrayList<>();

        try {
            HttpRequest request = HttpUtil.createGet(BAIDU_API_URL)
                    .header("User-Agent", getRandomUserAgent())
                    .header("Referer", "https://top.baidu.com/board?tab=realtime")
                    .header("Accept", "application/json")
                    .timeout(10000);

            HttpResponse response = request.execute();

            if (response.isOk()) {
                String json = response.body();
                items = parseApiData(json);
            }

            TimeUnit.MILLISECONDS.sleep(500);

        } catch (Exception e) {
            System.err.println("百度API请求失败: " + e.getMessage());
        }

        return items;
    }

    private List<HotItem> parseApiData(String json) {
        List<HotItem> normalItems = new ArrayList<>(); // 普通热搜
        HotItem pinnedItem = null; // 置顶热搜

        try {
            JSONObject jsonObject = JSONUtil.parseObj(json);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray cards = data.getJSONArray("cards");

            if (cards != null && cards.size() > 0) {
                // 1. 查找置顶内容（通常在第一个card的topContent字段）
                for (int i = 0; i < cards.size(); i++) {
                    JSONObject card = cards.getJSONObject(i);

                    // 检查是否有置顶内容
                    if (card.containsKey("topContent") && !card.getJSONArray("topContent").isEmpty()) {
                        pinnedItem = parsePinnedItem(card.getJSONArray("topContent"));
                        break;
                    }
                }

                // 2. 处理普通热搜列表
                JSONObject firstCard = cards.getJSONObject(0);
                JSONArray content = firstCard.getJSONArray("content");

                for (int i = 0; i < content.size(); i++) {
                    JSONObject item = content.getJSONObject(i);
                    HotItem hotItem = parseNormalItem(item, i);
                    if (hotItem != null) {
                        normalItems.add(hotItem);
                    }
                }
            }

            // 3. 合并结果：置顶热搜 + 普通热搜
            List<HotItem> allItems = new ArrayList<>();

            // 如果有置顶热搜，放在第一个位置
            if (pinnedItem != null) {
                allItems.add(pinnedItem);
                System.out.println("找到百度置顶热搜: " + pinnedItem.getTitle());
            }

            // 添加普通热搜（按热度倒序）
            allItems.addAll(sortByHotValue(normalItems));

            // 4. 重新设置排名
            for (int i = 0; i < allItems.size(); i++) {
                allItems.get(i).setRank(String.valueOf(i + 1));
            }

            return allItems;

        } catch (Exception e) {
            System.err.println("解析百度API数据失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 解析置顶热搜
     */
    private HotItem parsePinnedItem(JSONArray topContent) {
        try {
            if (topContent == null || topContent.isEmpty()) {
                return null;
            }

            // 取第一个置顶内容
            JSONObject pinnedData = topContent.getJSONObject(0);
            String title = pinnedData.getStr("word");
            String desc = pinnedData.getStr("desc", "");
            String hotValue = pinnedData.getStr("hotScore", "9999999"); // 置顶热度设为最高

            if (StrUtil.isBlank(title)) {
                return null;
            }

            HotItem pinnedItem = HotItem.create(PlatformTypeEnum.BAIDU, "0", title, hotValue);
            pinnedItem.setDescription("【置顶】" + desc);
            pinnedItem.setTag("置顶");
            pinnedItem.setTagColor("#ff3852"); // 红色标识置顶
            pinnedItem.setAd(false);

            // 设置URL
            String query = pinnedData.getStr("query", title);
            String url = generateBaiduUrl(query);
            pinnedItem.setUrl(url);

            return pinnedItem;

        } catch (Exception e) {
            System.err.println("解析百度置顶热搜失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 解析普通热搜项
     */
    private HotItem parseNormalItem(JSONObject item, int index) {
        try {
            String rank = String.valueOf(index + 1);
            String title = item.getStr("word");
            String hotValue = item.getStr("hotScore", "0");
            String desc = item.getStr("desc", "");
            String query = item.getStr("query", title);

            // 跳过空标题
            if (StrUtil.isBlank(title)) {
                return null;
            }

            HotItem hotItem = HotItem.create(PlatformTypeEnum.BAIDU, rank, title, hotValue);
            hotItem.setDescription(desc);
            hotItem.setTag(getBaiduTag(item));
            hotItem.setTagColor(getBaiduTagColor(hotItem.getTag()));
            hotItem.setAd(false);

            // 设置URL
            String url = generateBaiduUrl(query);
            hotItem.setUrl(url);

            // 趋势判断
            String hotChange = item.getStr("hotChange");
            if ("1".equals(hotChange)) {
                hotItem.setTrend("up");
            } else if ("2".equals(hotChange)) {
                hotItem.setTrend("down");
            } else {
                hotItem.setTrend("new");
            }

            return hotItem;

        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 按热度值倒序排序
     */
    private List<HotItem> sortByHotValue(List<HotItem> items) {
        items.sort((a, b) -> {
            try {
                int hotA = Integer.parseInt(a.getHotValue());
                int hotB = Integer.parseInt(b.getHotValue());
                return Integer.compare(hotB, hotA); // 倒序
            } catch (NumberFormatException e) {
                return 0;
            }
        });
        return items;
    }

    /**
     * 生成百度搜索URL
     */
    private String generateBaiduUrl(String query) {
        try {
            String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8.name());
            return "https://www.baidu.com/s?wd=" + encodedQuery;
        } catch (Exception e) {
            return "https://www.baidu.com/s?wd=" + query;
        }
    }

    private String getBaiduTag(JSONObject item) {
        String hotTag = item.getStr("hotTag");
        if (StrUtil.isNotBlank(hotTag)) {
            switch (hotTag) {
                case "1": return "新";
                case "2": return "热";
                case "3": return "爆";
                default: return "";
            }
        }
        return "";
    }

    private String getBaiduTagColor(String tag) {
        switch (tag) {
            case "爆": return "#ff3852";
            case "热": return "#ff9600";
            case "新": return "#00b4ff";
            case "置顶": return "#ff3852"; // 置顶使用红色
            default: return "#cccccc";
        }
    }

    private String getRandomUserAgent() {
        List<String> userAgents = CollUtil.newArrayList(
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0"
        );
        return RandomUtil.randomEle(userAgents);
    }
}
